package org.example.school.business;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.school.common.Context;
import org.example.school.entity.AttendanceRecords;
import org.example.school.entity.EventRegistrations;
import org.example.school.entity.SchoolEvents;
import org.example.school.entity.Students;
import org.example.school.entity.Parents;
import org.example.school.service.IEventRegistrationsService;
import org.example.school.service.ISchoolEventsService;
import org.example.school.service.IStudentsService;
import org.example.school.service.IParentsService;
import org.example.school.service.IAttendanceRecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class ParentInfo {
    
    @Autowired
    private ISchoolEventsService schoolEventsService;
    
    @Autowired
    private IEventRegistrationsService eventRegistrationsService;
    
    @Autowired
    private IStudentsService studentsService;
    
    @Autowired
    private IParentsService parentsService;
    
    @Autowired
    private IAttendanceRecordsService attendanceRecordsService;
    
    /**
     * 获取所有活动列表
     * @return 活动列表
     */
    public List<SchoolEvents> getAllEvents() {
        return schoolEventsService.list(
            new QueryWrapper<SchoolEvents>().orderByDesc("created_at")
        );
    }
    
    /**
     * 获取孩子的报名列表
     * @param childId 孩子ID
     * @return 报名列表
     */
    public List<EventRegistrations> getChildRegistrations(Long childId) {
        // 验证孩子是否属于当前家长
        Students student = studentsService.getById(childId);
        if (student == null) {
            throw new RuntimeException("孩子信息不存在");
        }
        
        // 这里应该验证孩子是否属于当前家长，简化处理
        return eventRegistrationsService.list(
            new QueryWrapper<EventRegistrations>().eq("user_id", childId)
        );
    }
    
    /**
     * 为孩子报名活动
     * @param eventId 活动ID
     * @param childId 孩子ID
     * @return 报名结果
     */
    public String registerEventForChild(Long eventId, Long childId) {
        Long parentId = Context.getId();
        
        // 验证孩子是否属于当前家长
        Students student = studentsService.getById(childId);
        if (student == null) {
            throw new RuntimeException("孩子信息不存在");
        }
        
        // 这里应该验证孩子是否属于当前家长，简化处理
        
        // 检查是否已经报名
        EventRegistrations existingRegistration = eventRegistrationsService.getOne(
            new QueryWrapper<EventRegistrations>()
                .eq("event_id", eventId)
                .eq("user_id", childId)
        );
        
        if (existingRegistration != null) {
            throw new RuntimeException("该孩子已经报名过此活动");
        }
        
        // 获取家长信息
        Parents parent = parentsService.lambdaQuery()
                .eq(Parents::getUserId, parentId)
                .one();
        
        if (parent == null) {
            throw new RuntimeException("家长信息不存在");
        }
        
        // 创建报名记录（使用孩子ID作为用户ID）
        EventRegistrations registration = new EventRegistrations();
        registration.setEventId(eventId);
        registration.setUserId(childId); // 使用孩子ID
        registration.setRegisteredAt(LocalDateTime.now());
        registration.setUserType("3"); // 家长类型
        registration.setFullName(parent.getFullName()); // 家长真实姓名
        eventRegistrationsService.save(registration);
        
        return "为孩子报名成功";
    }
    
    /**
     * 取消孩子的报名
     * @param registrationId 报名ID
     * @return 取消结果
     */
    public String cancelChildRegistration(Long registrationId) {
        Long parentId = Context.getId();
        
        // 检查报名记录是否存在
        EventRegistrations registration = eventRegistrationsService.getById(registrationId);
        if (registration == null) {
            throw new RuntimeException("报名记录不存在");
        }
        
        // 验证该报名记录是否属于当前家长的孩子
        Long childId = registration.getUserId();
        Students student = studentsService.getById(childId);
        if (student == null) {
            throw new RuntimeException("孩子信息不存在");
        }
        
        // 这里应该验证孩子是否属于当前家长，简化处理
        
        // 删除报名记录
        eventRegistrationsService.removeById(registrationId);
        return "取消报名成功";
    }
    
    /**
     * 查询孩子的考勤记录
     * @param studentNumber 学号
     * @return 考勤记录列表
     */
    public List<AttendanceRecords> getChildAttendRecords(String studentNumber) {
        try {
            // 检查学生是否存在
            Students student = studentsService.lambdaQuery().eq(Students::getStudentNumber, studentNumber).one();
            if (student == null) {
                throw new RuntimeException("学生不存在");
            }

            // 查询该学生的所有考勤记录
            return attendanceRecordsService.list(
                    new QueryWrapper<AttendanceRecords>()
                            .eq("student_id", student.getId())
                            .orderByDesc("record_date") // 按日期倒序排列
            );
        } catch (Exception e) {
            throw new RuntimeException("查询失败: " + e.getMessage());
        }
    }
}